package com.sx.pipeline.ui.ledger.device

import android.Manifest
import android.graphics.BitmapFactory
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ToastUtils
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lxj.xpopup.XPopup
import com.permissionx.guolindev.PermissionX
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.app.config.IntentKey
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.custom.dialog.CustomCommonPicket
import com.sx.pipeline.databinding.ActDeviceAddBinding
import com.sx.pipeline.ui.ledger.LedgerVM
import com.sx.pipeline.utils.AndroidUtil
import com.sx.pipeline.utils.CompressHelper
import com.sx.pipeline.utils.GlideEngine
import com.sx.pipeline.utils.PermissionHelper


/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 添加设备
 */
@Route(path = RoutePath.Mine.DEVICE_ADD)
class DeviceAddActivity : CYDataBindingBaseActivity<ActDeviceAddBinding, LedgerVM>
    (R.layout.act_device_add), View.OnClickListener {

    @JvmField
    @Autowired(name = IntentKey.ID)
    var deviceId: Int? = 0

    @JvmField
    @Autowired(name = IntentKey.TYPE)
    var type: Int? = 0  //1 添加设备  2编辑设备
    private var factoryTime = ""//出厂日期


    override fun initData() {
        super.initData()
        mBinding.setVariable(BR.onClick, this)
        mBinding.titleBar.leftView.setOnClickListener {
            finish()
        }
        //请求联系人列表
        mViewModel.getContacts()
        //自动回填 联系人 和联系电话
        mBinding.etContact.setText(mViewModel.mModel.getUserData()?.userName)
        mBinding.etContactPhone.setText(mViewModel.mModel.getUserData()?.phone)
        when (type) {
            1 -> {
                mBinding.titleBar.title = getString(R.string.txt_add_device)
                //获取单位信息
                mViewModel.getUserUnit()
            }
            else -> {
                mBinding.titleBar.title = getString(R.string.txt_edit_device)
                mBinding.tvDelete.visibility = View.VISIBLE
                deviceId?.let { mViewModel.getDeviceDetail(it) }
            }
        }
        initProductImages()

    }

    override fun initViewObservable() {
        super.initViewObservable()
        observe(mViewModel.userUnitEvent) {
            mBinding.tvDeviceUnit.text = it?.name
        }
        //上传的图片
        observe(mViewModel.uploadDataEvent) {
            mBinding.imageProduct.addImage(it)
        }

        //编辑设备 设备数据
        observe(mViewModel.deviceDetailDataEvent) {
            it?.let {
                //设备名称
                mBinding.etDeviceName.setText(it.name)
                //产品型号
                mBinding.etProductModel.setText(it.productModel)
                //出厂日期
                mBinding.tvFactoryDate.text = it.productionDate
                factoryTime = it.productionDate
                //产品制造厂家
                mBinding.etManufacturer.setText(it.manufacturer)
                //产品编号
                mBinding.etProductNumber.setText(it.productNumber)
                //设备所属单位
                mBinding.tvDeviceUnit.text = it.unitName
                //联系人
                mBinding.etContact.setText(it.contact)
                //联系电话
                mBinding.etContactPhone.setText(it.contactPhone)

                if (!TextUtils.isEmpty(it.productImage)) {
                    val imageList = it.productImage.split(",")
                    for (i in imageList) {
                        mBinding.imageProduct.addImage(i)
                    }
                }
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_principal -> {
                if (mViewModel.taskContactData.size == 0) {
                    ToastUtils.showShort("未获取到数据")
                    return
                }
                val popup = CustomCommonPicket(this, getString(R.string.txt_choose_principal))
                popup.setPickerData(mViewModel.taskContactData)
                popup.setCommonPickerListener { position, data ->
                    mBinding.etContact.setText(data)
                    mBinding.etContactPhone.setText(mViewModel.taskContactPhoneData[position])
                }
                XPopup.Builder(this)
                    .borderRadius(42f)
                    .isDarkTheme(false)
                    .asCustom(popup)
                    .show()
            }

            R.id.tv_submit -> {
                if (type == 1) {
                    //添加设备
                    mViewModel.userUnitEvent.value?.id?.let {
                        AndroidUtil.listToString(mBinding.imageProduct.imagePath)?.let { it1 ->
                            mViewModel.equipmentAdd(
                                mBinding.etDeviceName.text.toString(),
                                mBinding.etManufacturer.text.toString(),
                                mBinding.etProductModel.text.toString(),
                                mBinding.etProductNumber.text.toString(),
                                factoryTime,
                                it,
                                mBinding.etContact.text.toString(),
                                mBinding.etContactPhone.text.toString(),
                                it1
                            )
                        }
                    }
                } else {
                    //编辑设备
                    mViewModel.deviceDetailDataEvent.value?.unitId?.let {
                        AndroidUtil.listToString(mBinding.imageProduct.imagePath)?.let { it1 ->
                            deviceId?.let { it2 ->
                                mViewModel.equipmentEdit(
                                    it2,
                                    mBinding.etDeviceName.text.toString(),
                                    mBinding.etManufacturer.text.toString(),
                                    mBinding.etProductModel.text.toString(),
                                    mBinding.etProductNumber.text.toString(),
                                    factoryTime,
                                    it,
                                    mBinding.etContact.text.toString(),
                                    mBinding.etContactPhone.text.toString(),
                                    it1
                                )
                            }
                        }
                    }
                }

            }
            //选择出厂日期
            R.id.tv_factory_date -> {
                CardDatePickerDialog.builder(this)
                    .setTouchHideable(true)
                    .showBackNow(false)
                    .showFocusDateInfo(false)
                    .setWrapSelectorWheel(false)
                    .setTitle("选择出厂日期")
                    .showDateLabel(true)
                    .setBackGroundModel(CardDatePickerDialog.STACK)
                    .setDisplayType(
                        DateTimeConfig.YEAR,
                        DateTimeConfig.MONTH,
                        DateTimeConfig.DAY,
                    )
                    .setLabelText("年", "月")
                    .setOnChoose("选择") {
                        factoryTime = AndroidUtil.conversionTime(it, "yyyy-MM-dd") + " 00:00:000"
                        mBinding.tvFactoryDate.text =
                            factoryTime
                    }
                    .setOnCancel("关闭") {

                    }
                    .build().show()
            }
            R.id.tv_delete -> {
                XPopup.Builder(this)
                    .isDestroyOnDismiss(true)
                    .asConfirm(
                        getString(R.string.hint), getString(R.string.txt_confirm_delete_device),
                        getString(R.string.cancel), getString(R.string.confirm),
                        {
                            //请求删除设备
                            deviceId?.let { mViewModel.getEquipmentDelete(it) }
                        }, null, false
                    ).show()
            }
        }
    }


    //设备图片
    private fun initProductImages() {
        // 上传图片
        mBinding.imageProduct.initAdapter(3, 3)
        mBinding.imageProduct.setImageUploadListener {
            PermissionHelper.requestTip(this,"上次图片需要授权相机和读写权限",object :
                PermissionUtils.SimpleCallback{
                override fun onGranted() {
                    PictureSelector.create(this@DeviceAddActivity)
                        .openGallery(SelectMimeType.ofImage())
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setMaxSelectNum(3 - mBinding.imageProduct.imagePath.size)
                        .forResult(object : OnResultCallbackListener<LocalMedia?> {
                            override fun onResult(result: ArrayList<LocalMedia?>?) {
                                //循环上传图片
                                for (i in 0 until result?.size!!) {
                                    Log.d("okhttp", "" + result[i]?.realPath)
                                    //压缩图片
                                    val inputBitmap =
                                        BitmapFactory.decodeFile(result[i]?.realPath)
                                    val compressFile = CompressHelper.compressQuality(
                                        this@DeviceAddActivity,
                                        inputBitmap
                                    )
                                    mViewModel.uploadImage(compressFile)
                                }
                            }

                            override fun onCancel() {}
                        })

                }

                override fun onDenied() {
                    ToastUtils.showShort("请授权后再继续操作")
                }
            },Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA)
//
//            PermissionX.init(this)
//                .permissions(
//                    Manifest.permission.READ_EXTERNAL_STORAGE,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                    Manifest.permission.CAMERA
//                )
//                .onExplainRequestReason { scope, deniedList ->
//                    scope.showRequestReasonDialog(
//                        deniedList,
//                        "核心基础功能基于这些权限,请允许,否则影响app正常使用",
//                        "确认",
//                        "取消"
//                    )
//                }
//                .onForwardToSettings { scope, deniedList ->
//                    scope.showForwardToSettingsDialog(
//                        deniedList,
//                        "您需要手动在“设置”中允许必要的权限",
//                        "确定",
//                        "取消"
//                    )
//                }
//                .request { allGranted, grantedList, deniedList ->
//                    if (allGranted) {
//                        PictureSelector.create(this)
//                            .openGallery(SelectMimeType.ofImage())
//                            .setImageEngine(GlideEngine.createGlideEngine())
//                            .setMaxSelectNum(3 - mBinding.imageProduct.imagePath.size)
//                            .forResult(object : OnResultCallbackListener<LocalMedia?> {
//                                override fun onResult(result: ArrayList<LocalMedia?>?) {
//                                    //循环上传图片
//                                    for (i in 0 until result?.size!!) {
//                                        Log.d("okhttp", "" + result[i]?.realPath)
//                                        //压缩图片
//                                        val inputBitmap =
//                                            BitmapFactory.decodeFile(result[i]?.realPath)
//                                        val compressFile = CompressHelper.compressQuality(
//                                            this@DeviceAddActivity,
//                                            inputBitmap
//                                        )
//                                        mViewModel.uploadImage(compressFile)
//                                    }
//                                }
//
//                                override fun onCancel() {}
//                            })
//                    } else {
//                        ToastUtils.showShort(getString(R.string.txt_these_permissions_are_denied))
//                    }
//                }

        }
    }

}